<template>
  <div class="bottom-bar">
    <!-- 全选 -->
    <div @click="selectAll" class="check-content">
      <check-button :isChecked="isSelectAll" class="check-btn" />
      <span>全选</span>
    </div>
    <!-- 总金额 -->
    <div class="price">合计:{{ totalPrice }}</div>
    <!-- 总数量 -->
    <div @click="calcClick" class="calculate">去计算({{ checkNum }})</div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import CheckButton from "components/content/checkButton/CheckButton";

export default {
  name: "CartBottomBar",
  components: {
    CheckButton
  },
  computed: {
    ...mapGetters(["cartList"]),
    totalPrice() {
      return (
        "￥" +
        this.cartList
          .filter(item => {
            // 过滤选中的商品
            return item.checked;
          })
          .reduce((preValue, item) => {
            // 进行价格的累加，得出总价
            return (preValue += item.price * item.count);
          }, 0)
          .toFixed(2)
      );
    },
    checkNum() {
      return this.cartList
        .filter(item => item.checked)
        .reduce((preValue, item) => {
          return preValue + item.count;
        }, 0);
    },
    isSelectAll() {
      if (this.cartList.length === 0) {
        // 列表为空时
        return false;
      } else {
        // 列表不为空时
        return this.cartList.every(item => {
          return item.checked;
        });
      }
    }
  },
  methods: {
    selectAll() {
      /**
       * 注意：
       * 以下代码不能简化为:this.cartList.forEach(item => item.checked = !this.isSelectAll)；
       * 因为forEach中item.checked在改变，item.checked的改变会影响isSelectAll的值，isSelectAll反过来又会影响item.checked的值，会产生混乱；
       */
      // 全选 -> 全不选
      if (this.isSelectAll) {
        this.cartList.forEach(item => (item.checked = false));
      } else {
        // 全不选 -> 全选
        this.cartList.forEach(item => (item.checked = true));
      }
    },
    calcClick() {
      if (this.cartList.some(item => item.checked)) {
        // 只要有选中的商品就跳转
        this.$toast.show("跳转中……", 2000);
      } else {
        this.$toast.show("请选择要购买的商品", 2000);
      }
    }
  }
};
</script>
<style scoped>
.bottom-bar {
  position: relative;
  z-index: 9;
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: space-between;
  background-color: #eee;
}

.check-content {
  display: flex;
  align-items: center;
  margin-left: 10px;
}
.check-btn {
  line-height: 20px;
  margin-right: 5px;
}

.calculate {
  background-color: var(--color-high-text);
  color: #fff;
}
</style>
